<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { v4 as uuidv4 } from 'uuid'
import { getUsers, getStudent, getOrganize } from '../../util/SessionUtil'
import regexUtil from '../../util/RegexUtil'
import $ from 'jquery'
import 'bootstrap/dist/js/bootstrap'
import { DateTime } from 'luxon'
import { useRoute } from 'vue-router'
import PaymentDetail from '../../components/PaymentDetail.vue'
import PostalInfo from '../../components/PostalInfo.vue'
import { db } from '../../db/db'

const route = useRoute()

const donationSubdivisionTypeData: any = ref([])
const ptInfo: any = ref({})

const moneyChecked = ref([
  { checked: false, value: '5' },
  { checked: false, value: '10' },
  { checked: false, value: '50' },
  { checked: false, value: '100' },
  { checked: false, value: '200' },
  { checked: false, value: '500' }
])
const moneyInputValue = ref('')

const form = ref({
  donationSubdivisionTypeId: '',
  money: '',
  goodsName: '',
  goodsNumber: '',
  donor: '',
  donorPhoneNumber: ''
})
const formErr = ref({
  donationSubdivisionTypeId: false,
  money: false,
  goodsName: false,
  goodsNumber: false,
  donor: false,
  donorPhoneNumber: false
})
const formMsg = ref({
  donationSubdivisionTypeId: '',
  money: '',
  goodsName: '',
  goodsNumber: '',
  donor: '',
  donorPhoneNumber: ''
})

const users = getUsers()

onMounted(async () => {
  donationSubdivisionTypeData.value = await db.donationSubdivisionType.toArray()
  const pi = await db.platformInformation.toArray()
  ptInfo.value = pi.length > 0 ? pi[0] : {}
  if (users) {
    form.value.donor = users.realName
    if (users.usersTypeId == 4) {
      const student = await getStudent(users.username)
      form.value.donorPhoneNumber = student[0].phoneNumber
    } else if (users.usersTypeId == 3) {
      const organize = await getOrganize(users.username)
      form.value.donorPhoneNumber = organize[0].responsiblePersonPhoneNumber
    }
  }
})

const moneySelect = (index: number) => {
  for (let m = 0; m < moneyChecked.value.length; m++) {
    if (m != index) {
      moneyChecked.value[m].checked = false
    }
  }

  moneyChecked.value[index].checked = !moneyChecked.value[index].checked


  if (moneyChecked.value[index].checked) {
    form.value.money = moneyChecked.value[index].value

    formErr.value.money = false
    formMsg.value.money = ''
    moneyInputValue.value = ''
  } else {
    form.value.money = ''
  }
}

const moneyInput = () => {

  form.value.money = moneyInputValue.value

  if (moneyInputValue.value !== '') {
    for (let m in moneyChecked.value) {
      moneyChecked.value[m].checked = false
    }

    formErr.value.money = false
    formMsg.value.money = ''
  }
}

function checkDonationSubdivisionTypeId() {
  formErr.value.donationSubdivisionTypeId = false
  formMsg.value.donationSubdivisionTypeId = ''
  if (form.value.donationSubdivisionTypeId === '') {
    formErr.value.donationSubdivisionTypeId = true
    formMsg.value.donationSubdivisionTypeId = '请选择捐赠类型'
    return false
  }

  if (Number(form.value.donationSubdivisionTypeId) != 1) {
    for (let m in moneyChecked.value) {
      moneyChecked.value[m].checked = false
    }
    moneyInputValue.value = ''
    form.value.money = ''
  } else {
    form.value.goodsName = ''
    form.value.goodsNumber = ''
  }

  return true
}

function checkMoney() {
  formErr.value.money = false
  formMsg.value.money = ''
  if (Number(form.value.donationSubdivisionTypeId) == 1) {
    if (form.value.money === '') {
      formErr.value.money = true
      formMsg.value.money = '请选择或填写捐赠金额'
      return false
    }
  }

  return true
}

function checkGoodsName() {
  formErr.value.goodsName = false
  formMsg.value.goodsName = ''
  if (Number(form.value.donationSubdivisionTypeId) != 1) {
    if (form.value.goodsName === '') {
      formErr.value.goodsName = true
      formMsg.value.goodsName = '物品名称不能为空'
      return false
    }
  }

  return true
}

function checkGoodsNumber() {
  formErr.value.goodsNumber = false
  formMsg.value.goodsNumber = ''
  if (Number(form.value.donationSubdivisionTypeId) != 1) {
    if (form.value.goodsNumber === '') {
      formErr.value.goodsNumber = true
      formMsg.value.goodsNumber = '物品数量不能为空'
      return false
    }
  }
  return true
}

function checkDonorPhoneNumber() {
  formErr.value.donorPhoneNumber = false
  formMsg.value.donorPhoneNumber = ''
  if (form.value.donorPhoneNumber !== '') {
    if (!regexUtil.mobile.test(form.value.donorPhoneNumber)) {
      formErr.value.donorPhoneNumber = true
      formMsg.value.donorPhoneNumber = '手机号11位数字'
      return false
    }
  }
  return true
}

let tempDonationId = ''
const submitForm = () => {
  if (!checkDonationSubdivisionTypeId()) {
    return false
  }

  if (Number(form.value.donationSubdivisionTypeId) == 1) {
    if (!checkMoney()) {
      return false
    }
  } else {
    if (!checkGoodsName()) {
      return false
    }

    if (!checkGoodsNumber()) {
      return false
    }
  }

  if (!checkDonorPhoneNumber()) {
    return false
  }

  tempDonationId = addDonationData()
  if (Number(form.value.donationSubdivisionTypeId) == 1) {
    $('#paymentModal').modal('show')
  } else {
    $('#postalInfoModal').modal('show')
  }

}

const addDonationData = () => {
  const donationId = uuidv4()
  db.donation.add({
    donationId: donationId,
    donationTypeId: Number(route.params.donationTypeId),
    donationSubdivisionTypeId: Number(form.value.donationSubdivisionTypeId),
    money: Number(form.value.money),
    goodsName: form.value.goodsName,
    goodsNumber: Number(form.value.goodsNumber),
    donationDate: DateTime.now().toFormat('yyyy-LL-dd HH:mm:ss'),
    donor: form.value.donor,
    donorPhoneNumber: form.value.donorPhoneNumber,
    username: users ? users.username : '',
    salvationId: '',
    postalStatus: 0,
    payStatus: 0,
    purpose: ''
  })
  return donationId
}

const updatePaymentStatus = () => {
  db.donation.where('donationId').equals(tempDonationId).modify({ payStatus: 1 })
}

const paymentSuccessed = () => {
  updatePaymentStatus()
  $('#successModal').modal('show')
}

const closeModal = () => {
  $('#successModal').modal('hide')
  window.location.href = "/"
}

</script>
<template>
  <div class="container pt-5 pb-5">
    <section class="pt-5 pb-5" data-aos="fade-up">
      <div class="jumbotron jumbotron-fluid">
        <div class="container">
          <h1 class="display-4">捐赠 <font-awesome-icon icon="heart" class="text-danger" /></h1>
          <p class="lead">爱心捐赠，温暖传递。让我们携手参与，为社会的和谐发展贡献一份力量。</p>
        </div>
      </div>
      <div class="row">
        <div class="col-12">
          <form @submit.prevent="submitForm">
            <div class="form-group">
              <label for="donationSubdivisionTypeId" class="font-weight-bold">捐赠类型</label>
              <select class="form-control" :class="formErr.donationSubdivisionTypeId ? 'is-invalid' : ''"
                v-model="form.donationSubdivisionTypeId" @change="checkDonationSubdivisionTypeId">
                <option value="">请选择类型</option>
                <option v-for="donationSubdivisionType in donationSubdivisionTypeData"
                  :value="donationSubdivisionType.donationSubdivisionTypeId">
                  {{ donationSubdivisionType.donationSubdivisionTypeName }}
                </option>
              </select>
              <div class="invalid-feedback">
                {{ formMsg.donationSubdivisionTypeId }}
              </div>
            </div>
            <div class="form-group" v-if="Number(form.donationSubdivisionTypeId) == 1">
              <div class="form-row">
                <div class="col-md-2 col-sm-4">
                  <div class="custom-control custom-checkbox custom-control-inline">
                    <input class="custom-control-input" type="checkbox" name="moneyCheckBox" id="moneyCheckBox1"
                      value="5" @click="moneySelect(0)" :checked="moneyChecked[0].checked">
                    <label class="font-weight-bold custom-control-label" for="moneyCheckBox1">5元</label>
                  </div>
                </div>
                <div class="col-md-2 col-sm-4">
                  <div class="custom-control custom-checkbox custom-control-inline">
                    <input class="custom-control-input" type="checkbox" name="moneyCheckBox" id="moneyCheckBox2"
                      value="10" @click="moneySelect(1)" :checked="moneyChecked[1].checked">
                    <label class="font-weight-bold custom-control-label" for="moneyCheckBox2">10元</label>
                  </div>
                </div>
                <div class="col-md-2 col-sm-4">
                  <div class="custom-control custom-checkbox custom-control-inline">
                    <input class="custom-control-input" type="checkbox" name="moneyCheckBox" id="moneyCheckBox3"
                      value="50" @click="moneySelect(2)" :checked="moneyChecked[2].checked">
                    <label class="font-weight-bold custom-control-label" for="moneyCheckBox3">50元</label>
                  </div>
                </div>
                <div class="col-md-2 col-sm-4">
                  <div class="custom-control custom-checkbox custom-control-inline">
                    <input class="custom-control-input" type="checkbox" name="moneyCheckBox" id="moneyCheckBox4"
                      value="100" @click="moneySelect(3)" :checked="moneyChecked[3].checked">
                    <label class="font-weight-bold custom-control-label" for="moneyCheckBox4">100元</label>
                  </div>
                </div>
                <div class="col-md-2 col-sm-4">
                  <div class="custom-control custom-checkbox custom-control-inline">
                    <input class="custom-control-input" type="checkbox" name="moneyCheckBox" id="moneyCheckBox5"
                      value="200" @click="moneySelect(4)" :checked="moneyChecked[4].checked">
                    <label class="font-weight-bold custom-control-label" for="moneyCheckBox5">200元</label>
                  </div>
                </div>
                <div class="col-md-2 col-sm-4">
                  <div class="custom-control custom-checkbox custom-control-inline">
                    <input class="custom-control-input" type="checkbox" name="moneyCheckBox" id="moneyCheckBox6"
                      value="500" @click="moneySelect(5)" :checked="moneyChecked[5].checked">
                    <label class="font-weight-bold custom-control-label" for="moneyCheckBox6">500元</label>
                  </div>
                </div>
                <div class="col-md-4 col-xs-12">
                  <div class="input-group">
                    <input type="number" class="form-control" id="moneyCheckBox7" placeholder="其它金额"
                      v-model.number="moneyInputValue" @blur="moneyInput">
                    <div class="input-group-prepend">
                      <div class="input-group-text">元</div>
                    </div>
                  </div>
                </div>
              </div>

              <div class="invalid-feedback" style="display: block;">
                {{ formMsg.money }}
              </div>
            </div>
            <div class="form-group"
              v-if="Number(form.donationSubdivisionTypeId) != 1 && form.donationSubdivisionTypeId !== ''">
              <label for="address" class="font-weight-bold">物品名称</label>
              <input type="text" class="form-control" placeholder="物品名称" :class="formErr.goodsName ? 'is-invalid' : ''"
                v-model.trim="form.goodsName" @blur="checkGoodsName" />
              <div class="invalid-feedback">
                {{ formMsg.goodsName }}
              </div>
            </div>
            <div class="form-group"
              v-if="Number(form.donationSubdivisionTypeId) != 1 && form.donationSubdivisionTypeId !== ''">
              <label for="address" class="font-weight-bold">物品数量</label>
              <input type="number" class="form-control" placeholder="物品数量"
                :class="formErr.goodsNumber ? 'is-invalid' : ''" v-model.number="form.goodsNumber"
                @blur="checkGoodsNumber" />
              <div class="invalid-feedback">
                {{ formMsg.goodsNumber }}
              </div>
            </div>
            <div class="form-group">
              <label for="address" class="font-weight-bold">捐赠人(选填)</label>
              <input type="text" class="form-control" placeholder="捐赠人" :class="formErr.donor ? 'is-invalid' : ''"
                v-model.trim="form.donor" />
              <div class="invalid-feedback">
                {{ formMsg.donor }}
              </div>
              <small class="form-text text-muted">感谢您的捐赠！</small>
            </div>
            <div class="form-group">
              <label for="address" class="font-weight-bold">捐赠人联系方式(选填)</label>
              <input type="text" class="form-control" placeholder="捐赠人联系方式"
                :class="formErr.donorPhoneNumber ? 'is-invalid' : ''" v-model.trim="form.donorPhoneNumber"
                @blur="checkDonorPhoneNumber" />
              <div class="invalid-feedback">
                {{ formMsg.donorPhoneNumber }}
              </div>
            </div>
            <div class="text-center">
              <button type="submit" class="btn btn-danger">捐 赠</button>
            </div>
          </form>
        </div>
      </div>
    </section>
  </div>

  <!-- Modal -->
  <div class="modal fade" id="successModal" tabindex="-1" aria-labelledby="successModalLabel" aria-hidden="true">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title text-success" id="successModalLabel">捐赠成功</h5>
          <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true">&times;</span>
          </button>
        </div>
        <div class="modal-body">
          感谢您无私的捐赠，您的慷慨帮助让我们能够继续向前，完成我们的使命。
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" @click="closeModal">确定</button>
        </div>
      </div>
    </div>
  </div>

  <!--支付框-->
  <PaymentDetail :money="form.money" :platformInformationData="ptInfo" @payment-successed="paymentSuccessed" />
  <!--邮寄信息-->
  <PostalInfo :platformInformationData="ptInfo" />

</template>
